package com.csi.controller.role;

import com.alibaba.fastjson2.JSON;
import com.csi.domain.Role;
import com.csi.pojo.Result;
import com.csi.service.RoleService;
import com.csi.service.impl.RoleServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@WebServlet("/role/addController")
public class AddController extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("application/json;charset=utf-8");
        Result result = new Result<>();

        PrintWriter out = resp.getWriter();
        // 获取请求参数
        String roleName = null;
        String roleDesc = null;
        try {
            roleName = req.getParameter("roleName");
            roleDesc = req.getParameter("roleDesc");
        } catch (Exception e) {
            result.setCode(400);
            result.setMsg("参数转换异常");
            out.print(JSON.toJSONString(result));
            return;
        }

        RoleService roleService = new RoleServiceImpl();

        Map<String, Role> map = roleService.findAll();

        for (Role s : map.values()) {
            if (s.getRoleName().equals(roleName)){
                result.setCode(400);
                result.setMsg("角色已存在");
                out.print(JSON.toJSONString(result));
                return;
            }
        }

        try {
            roleService.add(roleName, roleDesc);
        } catch (Exception e) {
            result.setCode(400);
            result.setMsg("false");
            out.print(JSON.toJSONString(result));
            return;
        }

        result.setCode(200);
        result.setMsg("success");
        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();

    }
}
